package edu.worldskills.b;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTP {
    public static String doGet(String ip) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response;
        try {
            URL url = new URL(ip);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);

            InputStream in = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));



            response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (IOException e) {
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
//                    Log.e(TAG, "Error closing reader: " + e.getMessage());
                }
            }
            if (connection != null) {
                connection.disconnect();
            }

        }
    }

    public String doPost(String ip, JSONObject obj) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(ip);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            byte[] bytes = obj.toString().getBytes();
            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));

            OutputStream os = conn.getOutputStream();
            os.write(bytes);
            os.flush();
            os.close();

            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            InputStream input = conn.getInputStream();
            StringBuilder sb = new StringBuilder();
            int ss;
            while ((ss = input.read()) != -1) {
                sb.append((char) ss);
            }
            input.close();
            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}
